<?php

// 应用公共文件
function ll($arr)
{
    echo '<pre>';
    var_dump($arr);
    echo '<pre>';
}

function object2array($object)
{
    $array = array();
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    } else {
        $array = $object;
    }
    return $array;
}

// 缩略图
// $image = \think\Image::open('./storage/'.$savename);
// $image->thumb(150, 150)->save('./storage/thumb/thumb_'.$imgarr[1].'.'.$extarr[1]);

/**
 * API接口返回
 */
if (!function_exists('api_return')) {
    function api_return($code = 200, $msg = "", $data = [])
    {
        header('Content-Type:application/json; charset=utf-8');
        $rt['code'] = $code;
        $rt['msg'] = !empty($msg) ? $msg : config('apiCode') [$code];
        $rt['data'] = $data;
        exit(json_encode($rt));
    }
}

if (!function_exists('api_return_baidu')) {
    function api_return_baidu($code = 0, $msg = null, $data = [])
    {
        header('Content-Type:application/json; charset=utf-8');
        $rt['errno'] = $code;
        $rt['msg'] = $msg;
        $rt['data'] = $data;
        exit(json_encode($rt));
    }
}


/**
 * 过滤xss攻击
 */
if (!function_exists('remove_xss')) {
    function remove_xss($val)
    {
        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=@avascript:alert('XSS')>
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            // ;? matches the ;, which is optional
            // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

            // @ @ search for the hex values
            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
            // @ @ 0{0,7} matches '0' zero to seven times
            $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
        }

        // now the only remaining whitespace attacks are \t, \n, and \r
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);

        $found = true; // keep replacing as long as the previous round replaced something
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    // no replacements were made, so exit the loop
                    $found = false;
                }
            }
        }
        return $val;
    }
}

/**
 * 过滤参数
 */
if (!function_exists('filter_param')) {
    // 传递数据以易于阅读的样式格式化后输出并终止
    function filter_param($data)
    {
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                if (is_array($v)) {
                    continue;
                } else
                    $data[$k] = addslashes(remove_xss(trim($v)));
            }

        }
        return $data;
    }
}

/**
 * 获取子类
 */
if (!function_exists('get_child')) {
    function get_child($data)
    {
        $items = array();
        foreach ($data as $v) {
            //将数组存入$items,且$items的键为$data中的id
            $items[$v['id']] = $v;
        }
        $tree = [];
        foreach ($items as $item) {
            if (isset($items[$item['pid']]) && $item['pid'] != 0) {
                //通过pid判断$items中是否有对应的数组,$itms[0]不存在
                $items[$item['pid']]['child'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
}
/**
 * 获取子类children键值
 */
if (!function_exists('get_children')) {
    function get_children($data)
    {
        $items = array();
        foreach ($data as $v) {
            //将数组存入$items,且$items的键为$data中的id
            $items[$v['id']] = $v;
        }
        $tree = [];
        foreach ($items as $item) {
            if (isset($items[$item['pid']]) && $item['pid'] != 0) {
                //通过pid判断$items中是否有对应的数组,$itms[0]不存在
                $items[$item['pid']]['children'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
}

/**
 * 过滤敏感词
 */
if (!function_exists('filter_sensitive_words')) {
    function filter_sensitive_words($words = '')
    {
        $words = trim($words);
        if (!$words) {
            return '';
        }
//        cache('mgc', null);
//        $mgcArr = Db::name('mgc')->cache('mgc', 3600)->column('name');
//        $mgcArr = array_unique($mgcArr);
//        $words = str_ireplace($mgcArr, '*', $words, $i);
        return $words;
    }
}

/**
 * 按|分割成数组
 */
if (!function_exists('getExp')) {
    function getExp($str, $Symbol = "|")
    {
        if (empty($str)) {
            $data = [];
        } else {
            $data = array_filter(explode($Symbol, $str));
            $data = array_values($data);
        }
        return $data;
    }
}

/**
 * curl 通用请求
 * @param $url
 * @param $post
 * @param $cookie
 * @param $returnCookie
 * @return array|bool|string
 */
function curl_request($url, $post = false, $cookie = false, $returnCookie = false)
{
    $curl = curl_init();
    $this_header = array(
        "content-type:application/json"
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $this_header);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

//curl post
function post($url, $data, $this_header = [], $ssl = [])
{

    //初使化init方法
    $ch = curl_init();
//    if(!$this_header)
//        $this_header = array(
//            "content-type:application/json"
//        );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
    //指定URL
    curl_setopt($ch, CURLOPT_URL, $url);

    //设定请求后返回结果
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //声明使用POST方式来进行发送
    curl_setopt($ch, CURLOPT_POST, 1);

    //发送什么数据呢
    @curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    if (!$ssl) {
        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    } else {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSLCERT, $ssl['cert']); //client.
        curl_setopt($ch, CURLOPT_SSLKEY, $ssl['key']);
    }
    //忽略header头信息
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //设置超时时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);

    //发送请求
    $output = curl_exec($ch);

    //关闭curl
    curl_close($ch);

    //返回数据
    return $output;
}

//curl get
function get($url, $port = 80)
{
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置端口号
    if ($port != 80)
        curl_setopt($curl, CURLOPT_PORT, $port);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    return $data;
}

function cc_format($name)
{

    $temp_array = array();

    for ($i = 0; $i < strlen($name); $i++) {

        $ascii_code = ord($name[$i]);

        if ($ascii_code >= 65 && $ascii_code <= 90) {

            if ($i == 0) {

                $temp_array[] = chr($ascii_code + 32);

            } else {

                $temp_array[] = '_' . chr($ascii_code + 32);

            }

        } else {

            $temp_array[] = $name[$i];

        }

    }

    return implode('', $temp_array);

}

function getTimeDifference($time1, $time2)
{
    $secs = abs(strtotime($time1) - strtotime($time2));
    $h = $secs / 60 / 60;
    return floor($h / 24) . "天" . ($h % 24) . '小时';
}

/**
 * utf-8 转unicode
 *
 * @param string $name
 * @return string
 */
function unicode_encode($name)
{
//    $name = iconv('UTF-8', 'UCS-2', $name);
    $name = mb_convert_encoding($name, 'UCS-2');
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2) {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0) {   //两个字节的文字
            $str .= '_u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
            //$str .= base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
        } else {
            $str .= '_u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
            //$str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
        }
    }
//    $str = strtoupper($str);//转换为大写
    return $str;
}

/**
 *$strUnicode编码后的字符串
 *$encoding原始字符串的编码，默认GBK
 *$prefix编码字符串的前缀，默认"&#"
 *$postfix编码字符串的后缀，默认";"
 */
function unicode_decode($unicode_str)
{
    $json = '{"str":"' . $unicode_str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
}

function strposa($haystack, $needles = array(), $offset = 0)
{
    $chr = array();
    foreach ($needles as $needle) {
        $res = strpos($haystack, $needle, $offset);
        if ($res !== false) $chr[$needle] = $res;
    }
    if (empty($chr)) return false;
    return min($chr) + 1;
}

/**
 * 二维数组按指定key进行数量统计
 * @param $arr 二维数组
 * @param $groupBy 分组统计字段key
 * @return array
 */
function arrayGroupBy($arr, $groupBy)
{
    $result = array();
    foreach ($arr as $subArr) {
        $group = $subArr[$groupBy];
        if (!isset($result[$group])) {
            $result[$group] = 0;
        }
        $result[$group]++;
    }
    return $result;
}

/**
 * 计算两个经纬度之间的距离
 * @param $lng1 经度1
 * @param $lat1 纬度2
 * @param $lng2 经度2
 * @param $lat2 纬度2
 * @return float|int
 */
function getDistanceByCoor($lng1, $lat1, $lng2, $lat2)

{

    $EARTH_RADIUS = 6378137; //地球半径

    $RAD = pi() / 180.0;

    $radLat1 = $lat1 * $RAD;

    $radLat2 = $lat2 * $RAD;

    $a = $radLat1 - $radLat2; // 两点纬度差

    $b = ($lng1 - $lng2) * $RAD; // 两点经度差

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));

    $s = $s * $EARTH_RADIUS;

    $s = round($s * 10000) / 10000;

    return $s;

}

/**
 * 判断字符串中是否包含指定数组元素
 * @param $string 字符串
 * @param $array 数组
 * @return bool
 */
function strInArray($string, $array)
{
    foreach ($array as $url) {
        //if (strstr($string, $url)) { // mine version
        if (strpos($string, $url) !== FALSE) { // Yoshi version
            return true;
        }
    }
    return false;
}
